<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use think\Db;

/**
 * 商品
 *
 * @icon fa fa-circle-o
 */
class Add extends Backend
{
    
    /**
     * Add模型对象
     * @var \app\admin\model\goods\Add
     */
    protected $model = null;

    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Add;
        $this->view->assign("kindList", $this->model->getKindList());
        $this->view->assign("isSchoolList", $this->model->getIsSchoolList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->where(['is_school' => 1, 'is_delete' => 0, 'school_admin_id' => 0])
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','price','cover_pic']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /*
     * 查看课程详情
     * */
    public function detail($ids = '')
    {
        // 商品信息
        $goods =Db::name('goods')->alias('g')
            ->where(['g.id' => $ids, 'g.is_delete' => 0])
            ->field('g.id, g.name, g.price, g.detail, g.sort, g.cover_pic, g.goods_num, g.attr, g.use_attr')
            ->find();

        //轮播图
        $goods_pic_list = Db::name('goods_pic')->where(['goods_id' => $goods['id'], 'is_delete' => 0])->column('pic_url');

        //规格组
        $attr_group_list = [];
        $attr_data = json_decode($goods['attr'], true);
        $num = 0;
        foreach ($attr_data as $i => $attr_data_item) {
            foreach ($attr_data[$i]['attr_list'] as $j => $attr_list) {
                $attr_group = Db::name('attr_group')
                    ->where('id','in',DB::name('attr')->where('id', $attr_data[$i]['attr_list'][$j]['attr_id'])->distinct(true)->column('attr_group_id'))
                    ->find();
                if ($attr_group) {
                    $in_list = false;
                    foreach ($attr_group_list as $k => $exist_attr_group) {
                        if ($exist_attr_group['attr_group_name'] == $attr_group['attr_group_name']) {
                            $attr_item = [
                                'attr_id' => $attr_data[$i]['attr_list'][$j]['attr_id'],
                                'attr_name' => $attr_data[$i]['attr_list'][$j]['attr_name'],
                            ];
                            if (!in_array($attr_item, $attr_group_list[$k]['attr_list'])) {
                                $attr_group_list[$k]['attr_list'][] = $attr_item;
                            }
                            $in_list = true;
                        }
                    }
                    if (!$in_list) {
                        $attr_group_list[] = [
                            'attr_group_name' => $attr_group['attr_group_name'],
                            'attr_list' => [
                                [
                                    'attr_id' => $attr_data[$i]['attr_list'][$j]['attr_id'],
                                    'attr_name' => $attr_data[$i]['attr_list'][$j]['attr_name'],
                                ],
                            ],
                        ];
                    }
                }
            }
            $num += $attr_data_item['num'];
        }
        $goods['goods_num'] = $num;

        //规格
        $attr_row_list = [];
        if ($goods['use_attr']) {
            $attr_row_list = json_decode($goods['attr'], true);
            foreach ($attr_row_list as $i => $attr_row) {
                foreach ($attr_row['attr_list'] as $j => $attr) {
                    $group = Db::name('attr_group')->where('id', 'in', Db::name('attr')->where(['id' => $attr['attr_id']])->column('attr_group_id'))->find();
                    $attr_row_list[$i]['attr_list'][$j]['attr_group_name'] = $group ? $group['attr_group_name'] : '';
                }
            }
        }

        $this->assign('goods', $goods);
        $this->assign('goods_pic_list', $goods_pic_list);
        $this->assign('attr_group_list', $attr_group_list);
        $this->assign('attr_row_list', $attr_row_list);

        return $this->view->fetch();
    }

    /*
     * 添加校外课程
     * */
    public function add($ids = "")
    {
        $row = $this->model->get($ids);
        if(!$row){
            $this->error(__("No results were found"));
        }
        $rst = array(
            'code' => 0,
            'msg' => '添加失败, 请重试!',
            'data' => '$row',
            'url' => '',
            'wait' => '3'
        );
        if($this->request->isPost()){
            $row->school_admin_id = $this->auth->id;
            $row->save();
            $rst['code'] = 1;
            $rst['msg'] = '添加成功';
        }

        return json($rst);
    }


}
